package com.zzh.h265toupin

import android.os.Bundle
import android.util.Log
import android.view.Surface
import android.view.SurfaceHolder
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.zzh.h265toupin.databinding.ActivityPlayerBinding
import com.zzh.h265toupin.utils.NetworkUtil

class TouPinPlayerActivity : AppCompatActivity() {
    private lateinit var binding: ActivityPlayerBinding
    private var h265Decode: H265Decode? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityPlayerBinding.inflate(layoutInflater)
        setContentView(binding.root)
        initView()
    }

    private fun initView() {
        binding.btPlay.setOnClickListener {
            val ip = binding.etPullIp.text.toString()
            val port = binding.etPullPort.text.toString()
            h265Decode?.startPlay("ws://$ip:$port")
        }

        binding.surface.holder.addCallback(object : SurfaceHolder.Callback {
            override fun surfaceCreated(holder: SurfaceHolder) {
                initDecoder(holder.surface)
            }

            override fun surfaceChanged(
                holder: SurfaceHolder,
                format: Int,
                width: Int,
                height: Int
            ) {

            }

            override fun surfaceDestroyed(holder: SurfaceHolder?) {
            }

        })
    }


    private fun initDecoder(surface: Surface) {
        h265Decode = H265Decode(surface)
        h265Decode!!.setConnectCallback {
            Log.e("TAG_TouPinPlayer", "connect:$it")
            runOnUiThread {
                if (it) {
                    Toast.makeText(this, "远程已连接", Toast.LENGTH_SHORT).show()
                } else {
                    Toast.makeText(this, "远程已断开", Toast.LENGTH_SHORT).show()
                    finish()
                }
            }

        }
    }

    override fun onDestroy() {
        super.onDestroy()
        h265Decode?.close()
        h265Decode = null
    }
}